<template>
    <div class="app-container">
        <VxeBasicTable ref="xGrid" @checkbox-change="handleSelectionChange" style="height: 100%" tableName="sys_post">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:post:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:post:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:post:remove']">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_normal_disable" :value="row.status" />
            </template>
            <template #action="{ row }">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:post:edit']">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:post:remove']">删除</el-button>
            </template>
        </VxeBasicTable>
        <!-- 添加或修改岗位对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="postRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="岗位名称" prop="postName">
                    <el-input v-model="form.postName" placeholder="请输入岗位名称" />
                </el-form-item>
                <el-form-item label="岗位编码" prop="postCode">
                    <el-input v-model="form.postCode" placeholder="请输入编码名称" />
                </el-form-item>
                <el-form-item label="岗位顺序" prop="postSort">
                    <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
                </el-form-item>
                <el-form-item label="岗位状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="Post">
    import { getCurrentInstance, ref, reactive, toRefs } from "vue";
    import { pagePost, addPost, delPost, getPost, updatePost } from "@/api/system/post";
    import { VxeGridInstance, VxeGridProps, VxeGridDefines } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import VxeBasicTable from "@/components/ElementRender";
    const { proxy } = getCurrentInstance() as any;
    const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

    const open = ref(false);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const title = ref("");
    const data: any = reactive({
        form: {},
        rules: {
            postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
            postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
            postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
        },
    });
    const { form, rules } = toRefs(data);
    const xGrid = ref({} as VxeGridInstance);
    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "5",
        height: "auto",
        rowId: "postId",
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 100,
            titleAlign: "right",
            items: [
                {
                    field: "postCode",
                    title: "岗位编码",
                    span: 5,
                    itemRender: { name: "$input", props: { placeholder: "请输入岗位编码" } },
                },
                {
                    field: "postName",
                    title: "岗位名称",
                    span: 5,
                    itemRender: { name: "$input", props: { placeholder: "请输入岗位名称" } },
                },
                {
                    field: "status",
                    title: "状态",
                    span: 5,
                    itemRender: {
                        name: "$select",
                        options: sys_normal_disable,
                    },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
            export: proxy.$auth.hasPermi("system:post:export"),
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        proxyConfig: {
            paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }: any) => {
                    const queryParams: any = Object.assign({}, form);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }: any) => {
                        queryParams[property] = values.join(",");
                    });
                    return pagePost({
                        page: {
                            current: page.currentPage,
                            size: page.pageSize,
                        },

                        ...queryParams,
                        ...params,
                    }).then((response) => {
                        return response;
                    });
                },
            },
        },
        checkboxConfig: {
            trigger: "row",
        },
        columns: [
            { type: "radio", width: 60 },
            {
                field: "postId",
                title: "岗位编号",
                sortable: true,
            },
            {
                field: "postCode",
                title: "岗位编码",
                sortable: true,
            },
            {
                field: "postName",
                title: "岗位名称",
                sortable: true,
            },
            {
                field: "postSort",
                title: "岗位排序",
                sortable: true,
            },
            {
                field: "status",
                title: "状态",
                filters: sys_normal_disable,
                slots: {
                    default: "slotStatus",
                },
            },
            {
                field: "createTime",
                title: "创建时间",
                visible: false,
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
            {
                field: "remark",
                title: "备注",
                sortable: true,
            },
            {
                title: "操作",
                width: 150,
                align: "center",
                fixed: "right",
                slots: { default: "action" },
            },
        ],
    });

    /** 取消按钮 */
    function cancel() {
        open.value = false;
        reset();
    }
    /** 表单重置 */
    function reset() {
        form.value = {
            postId: undefined,
            postCode: undefined,
            postName: undefined,
            postSort: 0,
            status: "0",
            remark: undefined,
        };
        proxy.resetForm("postRef");
    }
    /** 多选框选中数据 */
    function handleSelectionChange(selection: any) {
        ids.value = selection.records.map((item: any) => item.postId);
        single.value = selection.records.length != 1;
        multiple.value = !selection.records.length;
    }
    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加岗位";
    }
    /** 修改按钮操作 */
    function handleUpdate(row: any) {
        reset();
        const postId = row.postId || ids.value;
        getPost(postId).then((response) => {
            form.value = response.data;
            open.value = true;
            title.value = "修改岗位";
        });
    }
    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["postRef"].validate((valid: any) => {
            if (valid) {
                if (form.value.postId != undefined) {
                    updatePost(form.value).then((response) => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        xGrid.value.commitProxy("reload");
                    });
                } else {
                    addPost(form.value).then((response) => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        xGrid.value.commitProxy("reload");
                    });
                }
            }
        });
    }
    /** 删除按钮操作 */
    function handleDelete(row: any) {
        const postIds = row.postId || ids.value;
        proxy.$modal
            .confirm('是否确认删除岗位编号为"' + postIds + '"的数据项？')
            .then(function () {
                return delPost(postIds);
            })
            .then(() => {
                xGrid.value.commitProxy("reload");
                proxy.$modal.msgSuccess("删除成功");
            })
            .catch(() => {});
    }
    /** 导出按钮操作 */
    // function handleExport() {
    //     proxy.download(
    //         "system/post/export",
    //         {
    //             ...queryParams.value,
    //         },
    //         `post_${new Date().getTime()}.xlsx`
    //     );
    // }
</script>
